package com.erclab.xbuilder.db;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.dataAccess.ApplicationDataSource;
import com.erclab.internal.xpresso.dataAccess.Query;
import com.erclab.internal.xpresso.exceptions.DataSourceException;
import com.erclab.xbuilder.exception.DBManagerException;

public class MysqlDatabaseManager implements DatabaseManager {

	protected ApplicationDataSource ads;
	
	public MysqlDatabaseManager(){
		int idDatasource = Integer.parseInt(Settings.getProperty("xbuilder_app_data.datasource"));		
		ads = Settings.getRepository().getApplicationDataSource(idDatasource);
		
	}
	
	
	public void createTable(String tableName, TableColumn[] columns) throws DBManagerException {
		
		StringBuffer query = new StringBuffer();
		query.append("CREATE TABLE " +  tableName + " (");
		query.append("Id" + tableName + " INT NOT NULL PRIMARY KEY AUTO_INCREMENT,");
		
		if (columns != null){
			for (int i = 0; i < columns.length; i++){
				query.append(columns[i].getColumnName() + " " + columns[i].getDataType());
			}
		}
		query.append("created TIMESTAMP DEFAULT NOW());");
		
		Query q = new Query();
		q.setQuery(query.toString());
		q.setValues(new String[0]);
		
		try {
			ads.executeQuery(q);
		} catch (DataSourceException e) {
			throw new DBManagerException("An error ocurred creating table.", e);
		}
	}

	public void alterTable(String tableName, String command) throws DBManagerException {

		Query q = new Query();
		q.setQuery("ALTER TABLE " + tableName + " " + command);
		q.setValues(new String[0]);		
		
		try {
			ads.executeQuery(q);
		} catch (DataSourceException e) {
			throw new DBManagerException("An error ocurred altering the table.", e);
		}
		
	}
	
	public void addColumnToTable(String tableName, TableColumn column) throws DBManagerException {
		String command = " ADD " + column.getColumnName() + " " + column.getDataType();
		this.alterTable(tableName, command);
	}


	public void dropTable(String tableName) throws DBManagerException {
		Query q = new Query();
		q.setQuery("DROP TABLE " + tableName + ";");
		q.setValues(new String[0]);		
		
		try {
			ads.executeQuery(q);
		} catch (DataSourceException e) {
			throw new DBManagerException("An error ocurred dropping the table.", e);
		}
	}


	public void dropColumn(String tableName, TableColumn column) throws DBManagerException {
		String command = " DROP " + column.getColumnName();
		this.alterTable(tableName, command);	
		
	}
	
	

}
